import Vuex from 'vuex'
import Vue from "vue";
import router from "@/router";
import {handleTree} from "@/plugins/handleTree";
import {getCurrUserMenu, getPermissions} from "@/api/menu";

Vue.use(Vuex)

const store = new Vuex.Store({
  //state 中存放的就是全局的共享数据
  state: {
    routes: [],
    menus: [],
    menuRouteList: ['-1'],
    permissions: []
  },
  mutations: {
    SET_ROUTES(state, routes) {
      state.routes = routes
    },
    SET_MENUS(state, menus) {
      state.menus = menus
    },
    SET_MENUROUTELIST(state, menuRouteList) {
      state.menuRouteList = menuRouteList
    },
    SET_PERMISSIONS: (state, permissions) => {
      state.permissions = permissions
    }
  },
  actions: {
    addMenuAndRouter({commit}) {
      return new Promise(resolve => {
        getCurrUserMenu().then((resp) => {
          if (resp.data.code === 200 && resp.data.data.menuList.length != 0) {
            commit('SET_MENUS', handleTree(resp.data.data.menuList, "menuId"))  //将后端返回的list数据转化为树结构
            const routes = filterRoutes(this.state.menus)
            router.addRoutes(routes)
            commit('SET_ROUTES', routes)
            commit('SET_MENUROUTELIST', resp.data.data.menuList)
            resolve(routes)
          } else {
            commit('SET_MENUROUTELIST', [])
            commit('SET_MENUS', [])
            commit('SET_ROUTES', [])
            resolve(false)
          }
        })
      })
    },
    // 获取权限信息
    getPermissions({commit, state}) {
      return new Promise((resolve, reject) => {
        getPermissions().then(res => {
          if (res.data.data && res.data.data.length > 0) { // 验证返回的permissions是否是一个非空数组
            commit('SET_PERMISSIONS', res.data.data)
          } else {
            commit('SET_PERMISSIONS', [])
          }
          resolve(res)
        }).catch(error => {
          reject(error)
        })
      })
    },
  },
  getters: {
    permissions: state => state.permissions,
  }
})

function filterRoutes(data) {
  let arr = [] // 整理后台数据，转换为添加路由的格式
  let child = []
  filterChild(data,child)
  arr.push({
    name: 'index',
    path: '/index',
    component: () => import('../components/Main'),
    children: child
  })
  return arr
}

function filterChild(data,child) {
  data.filter((val) => {
    if (val.children && val.children.length) {
      filterChild(val.children,child)
    }
    if(val.menuUrl && val.menuUrl.length){
      child.push({
        name: val.menuUrl,
        path: '/' + val.menuUrl,
        component: () => import('../' + val.component)
      })
    }
  })
}

export default store
